package com.example.kotlindemo.modules.network

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.kotlindemo.R

class UserInfoFragment: Fragment() {

    private lateinit var tokenTextView: TextView
    private lateinit var usernameTextView: TextView
    private lateinit var avatarImageView: ImageView

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_user_info, container , false)
        tokenTextView = view.findViewById<TextView>(R.id.user_token)
        usernameTextView = view.findViewById<TextView>(R.id.user_name)
        avatarImageView = view.findViewById<ImageView>(R.id.user_avatar)
        return view
    }

    fun updateUserInfo(userResponse: UserResponse) {
        tokenTextView.setText(userResponse.token)
        usernameTextView.setText(userResponse.username)
        // 使用 Glide 加载头像
        Glide.with(this)
            .load(userResponse.avatar)
            .placeholder(R.drawable.bg_completed_item_gradient) // 占位图
            .error(R.drawable.bg_checkmark_pending) // 错误图
            .diskCacheStrategy(DiskCacheStrategy.ALL) // 缓存策略
            .into(avatarImageView)
    }

    fun showError(error: String?) {
        tokenTextView.text = error
        usernameTextView.text = ""
        avatarImageView.setImageDrawable(null)
    }

}